import { uuid } from 'vue-uuid'
import { FILE_TYPE_CONTENT, FILE_TYPE, DATEFORMAT, formatDateComp } from '../const/applyForm/fieldItem'
import dataEleApi from '@/api/dataElement'
import Vue from 'vue'

// 根据指标值属性生成配置表单json
export const formatIndicatorDesc = (formDesc, label) => {
  // 生成文本配置
  switch (formDesc.type) {
    case 0:
      return {
        id: uuid.v1(),
        type: 'input',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: formDesc.attrs
      }
    case 1:
      return {
        id: uuid.v1(),
        type: 'textarea',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          autosizeType: 'switch', // 自适应高度
          maxlength: formDesc.attrs.maxlength
        }
      }
    case 2:
      return {
        id: uuid.v1(),
        type: 'radio',
        label: label,
        labelWidth: '170px',
        isOptions: true,
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        rules: [{ required: formDesc.control === 1 ? true : false, type: 'string', message: label + '必填' }],
        options: formDesc.options,
        attrs: { size: 'medium' }
      }
    case 3:
      return {
        id: uuid.v1(),
        type: 'checkbox',
        label: label,
        labelWidth: '170px',
        layout: 9,
        rules: [{ required: formDesc.control === 1 ? true : false, type: 'array', message: label + '必填' }],
        isOptions: true,
        options: formDesc.options,
        attrs: { size: 'medium' }
      }
    case 4:
      return {
        id: uuid.v1(),
        type: 'select',
        label: label,
        labelWidth: '170px',
        isOptions: true,
        rules: [
          {
            required: formDesc.control === 1 ? true : false,
            type: formDesc.selectedOption === 0 ? 'string' : 'array',
            message: label + '必填'
          }
        ],
        layout: 9,
        isOption: true,
        options: formDesc.options,
        attrs: {
          multiple: formDesc.selectedOption === 0 ? false : true
        }
      }
    case 5:
      return {
        id: uuid.v1(),
        type: 'number',
        label: label,
        labelWidth: '170px',
        class: formDesc.numberType === 3 ? 'my-input-number' : '',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          min: 0,
          max: formDesc.numberType === 3 ? 100 : 100000000000,
          precision: formDesc.numberType === 3 ? 2 : formDesc.numberType,
          step: 1
          // controlsPosition: "right"
        }
        // attrs: formDesc.attrs
      }
    case 6:
      return {
        id: uuid.v1(),
        type: 'upload-file',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          limit: formDesc.limit,
          isShowSize: false,
          isShowTip: false,
          multiple: true,
          action: dataEleApi.getDataUploadUrl(),
          fileType: supportedExtensions(formDesc.fileTypeArr),
          // fileSize: 32,
          headers: { authorization: '' },
          data: {
            bizId: '0'
          }
          // responseFn(response, file) {
          //   // 根据响应结果, 设置 URL
          //   return {
          //     name: file.name,
          //     url: URL.createObjectURL(file.raw),
          //     size: file.size
          //   }
          // }
        }
        // attrs: formDesc.attrs
      }
    case 7:
      return {
        id: uuid.v1(),
        type: formatDateComp(formDesc.dateType),
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          format: DATEFORMAT[formDesc.dateType]
          // valueFormat: DATEFORMAT[formDesc.dateType]
        }
        // attrs: formDesc.attrs
      }
    case 8:
      return {
        id: uuid.v1(),
        type: 'rate',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false
        // attrs: formDesc.attrs
      }
    case 9:
      return {
        id: uuid.v1(),
        type: 'table-editor',
        label: label,
        labelWidth: '170px',
        layout: 22,
        break: true,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          isShowReferenceData: true,
          isShowDelete: false,
          rules: formDesc.tableDesc.attrs.rules,
          newColumnValues: {},
          columns: formDesc.tableDesc.attrs.columns
        },
        default: formDesc.tableDesc.default
      }

    // 图片上传
    case 10:
      return {
        id: uuid.v1(),
        type: 'image-uploader',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: {
          action: dataEleApi.getDataUploadUrl(),
          headers: {},
          multiple: true,
          data: {
            bizId: '0'
          }
          // responseFn(response, file, fileList) {
          //   // 根据响应结果, 设置 URL
          //   return file.url
          // }
        }
      }
    case 11:
      return {
        id: uuid.v1(),
        type: 'formula',
        label: label,
        labelWidth: '170px',
        layout: 9,
        required: formDesc.control === 1 ? true : false,
        attrs: formDesc.attrs
      }
    // case 13:
    //   return {
    //     id: uuid.v1(),
    //     type: "formula",
    //     label: label,
    //     layout: 9,
    //     required: formDesc.control === 1 ? true : false,
    //     attrs: formDesc.attrs
    //   }
    // case 16:
    //   return {
    //     id: uuid.v1(),
    //     label: '',
    //     type: 'text',
    //     default: label,
    //     layout: 23,
    //     labelWidth: '0',
    //     class: 'title',
    //     maxlength: 300,
    //   }
  }
}

// 根据附件属性设置生成对应组件json
export const formatFieldComp = formDesc => {
  switch (formDesc.type) {
    case 0:
      return {
        unique_key: {
          id: '',
          type: 'input',
          isShowLabel: false,
          default: '',
          label: '',
          layout: 24,
          attrs: {
            disabled: true,
            placeholder: '请输入单行文本'
          }
        }
      }
    case 1:
      return {
        unique_key: {
          id: '',
          type: 'textarea',
          isShowLabel: false,
          label: '',
          default: '',
          layout: 24,
          attrs: {
            disabled: true,
            placeholder: '请输入多行文本',
            autosizeType: 'switch' // 自适应高度
          }
        }
      }
    case 2:
      return {
        unique_key: {
          id: '',
          type: 'radio',
          label: '',
          isOptions: true,
          layout: 24,
          options: formDesc.options,
          attrs: { size: 'medium', disabled: true }
        }
      }
    case 3:
      return {
        unique_key: {
          id: '',
          type: 'checkbox',
          label: '',
          isOptions: true,
          layout: 24,
          options: formDesc.options,
          attrs: { size: 'medium', disabled: true }
        }
      }
    case 4:
      return {
        unique_key: {
          id: '',
          type: 'select',
          label: '',
          isOptions: true,
          layout: 24,
          options: formDesc.options,
          attrs: {
            disabled: false,
            multiple: formDesc.selectedOption === 0 ? false : true
          }
        }
      }
    case 5:
      return {
        unique_key: {
          id: '',
          type: 'number',
          label: '',
          layout: 24,
          attrs: { disabled: true }
        }
      }
    case 6:
      return {
        unique_key: {
          id: '',
          type: 'upload-file',
          label: '',
          layout: 24,
          attrs: {
            action: '//',
            disabled: false,
            isShowSize: false
          }
        }
      }
    case 7:
      return {
        unique_key: {
          id: '',
          type: 'datetime',
          label: '',
          layout: 24,
          attrs: { disabled: true }
        }
      }
    // case 8:
    //   return {
    //     unique_key: {
    //       id: '',
    //       type: 'rate',
    //       label: '',
    //       layout: 24,
    //       attrs: {}
    //     }
    //   }
    case 9:
      return {
        unique_key: {
          id: '',
          type: 'table-editor',
          label: '',
          layout: 24,
          attrs: {
            isShowReferenceData: true,
            isShowDelete: false,
            columns: formDesc.tableDesc.attrs.columns,
          },
          default: formDesc.tableDesc.default
        }
      }
    case 10:
      return {
        unique_key: {
          id: '',
          type: 'image-uploader',
          label: '',
          layout: 24,
          attrs: {
            action: dataEleApi.getDataUploadUrl(),
            headers: {
              authorization: ''
            },
            data: {
              bizId: '0'
            }
          }
        }
      }
    // case 16:
    //   return {
    //     unique_key: {
    //       id: '',
    //       type: 'text',
    //       label: '',
    //       layout: 24,
    //       default: '标题',
    //       class: 'titleComponent'
    //     }
    //   }
  }
}

// 根据备注属性设置生成配置表单json
export const formatNotesDesc = formDesc => {
  return {
    id: uuid.v1(),
    type: 'input',
    label: '备注',
    labelWidth: '170px',
    layout: 9,
    required: formDesc.require === 1 ? true : false,
    attrs: {
      maxlength: formDesc.maxlength
    }
  }
}

const supportedExtensions = fileType => {
  if (fileType.includes(FILE_TYPE['NO_LIMIT'])) {
    return null
  }
  const extensions = fileType.reduce((acc, currentType) => {
    // 检查当前类型是否在FILE_TYPE_CONTENT中有定义
    if (FILE_TYPE_CONTENT[currentType]) {
      // 如果有，将其扩展名数组添加到累加器中
      return [...acc, ...FILE_TYPE_CONTENT[currentType]]
    }
    return acc
  }, [])
  return extensions
}
// 根据附件属性设置生成配置表单json
export const formatFilesDesc = (formDesc) => {
  return {
    id: uuid.v1(),
    type: 'upload-file',
    layout: 5,
    label: '',
    labelWidth: '0',
    required: formDesc.require === 1 ? true : false,
    attrs: {
      limit: formDesc.limit,
      isCanDownload: true,
      isCanDelete: true,
      isShowTip: false,
      multiple: true,
      // showFileList: true,
      fileType: supportedExtensions(formDesc.fileType),
      action: dataEleApi.getDataUploadUrl(),
      headers: { authorization: '' }, // 渲染时处理
      data: {
        bizId: '0'
      }
      // responseFn(response, file) {
      //   console.log("responseFn", response, file)
      //   // 根据响应结果, 设置 URL
      //   return {
      //     name: file.name,
      //     url: URL.createObjectURL(file.raw),
      //     // size: file.size
      //   }
      // },
    }
  }
}

// 生成附件列表展示组件
// export const formatFileList = (fileList) => {
//   return {
//     id: uuid.v1(),
//     type: "file-list",
//     label: '',
//     layout: 5,
//   }
// }

// 生成图片列表展示组件
export const formatImgList = (imgList) => {
  return {
    id: uuid.v1(),
    type: "img-list",
    label: '',
    layout: 24,
    default: imgList
  }
}

// 生成非子节点的标题
export const formatTitleDesc = (title, isBreak = false) => {
  return {
    id: uuid.v1(),
    label: '',
    type: 'text',
    default: title,
    layout: 23,
    labelWidth: '0',
    class: 'title',
    maxlength: 300,
    break: isBreak
  }
}

// 生成tooltip配置json
export const formatTooltipDesc = (tooltip, isBreak = false, isRight) => {
  if (tooltip) {
    return {
      id: uuid.v1(),
      label: '',
      type: 'tooltip',
      default: tooltip,
      layout: 1,
      labelWidth: '0',
      break: isBreak,
      attrs: {
        isRight: isRight ? isRight : false
      }
    }
  }
  else {
    return {
      id: uuid.v1(),
      label: '',
      labelWidth: '0',
      type: 'text',
      default: '',
      layout: 1,
      isShowLabel: false
    }
  }
}

// formDesc的格式转换(将数组转为对象)
export const convertFormDesc = formDesc => {
  const newFormDesc = formDesc.reduce((acc, item) => {
    acc[item.id] = { ...item }
    return acc
  }, {})
  return newFormDesc
}

const findNodeById = (id, treeData) => {
  for (let node of treeData) {
    if (node.id === id) {
      return node
    }
    if (node.children) {
      let found = findNodeById(id, node.children)
      if (found) return found
    }
  }
  return null
}
// 根据父节点ID添加子节点(如果当前是叶子节点，则生成文件夹添加children，并把原先的formDesc替换为text组件)
export const addNodeToChildren = (parentId, isLeaf, treeData, newNode) => {
  let parentNode = findNodeById(parentId, treeData)
  if (parentNode) {
    if (!parentNode.hasOwnProperty('children')) {
      Vue.set(parentNode, 'children', [])
    }
    parentNode.children.push(newNode)
    // 控制换行
    parentNode.children[parentNode.children.length - 1].formDesc[0].break = true
    if (isLeaf) {
      parentNode['formDesc'] = []
      parentNode.tip && parentNode['formDesc'].push(formatTooltipDesc(parentNode.tip, false, true))
      parentNode['formDesc'].push(formatTitleDesc(parentNode.label))
      // 控制换行
      parentNode.formDesc[0].break = true
    }
  } else {
    throw new Error('找不到父节点')
  }
}

// 修改节点配置项
export const updateNode = (parentId, treeData, newNode, isLeaf) => {
  let currentNode = findNodeById(parentId, treeData)
  currentNode.label = newNode.label
  currentNode.tip = newNode.tip
  if (isLeaf) {
    currentNode.attributes = newNode.attributes
    currentNode.formDesc = newNode.formDesc
    // 控制换行
    currentNode.formDesc[0].break = true
  } else {
    currentNode['formDesc'] = []
    newNode.tip && currentNode['formDesc'].push(formatTooltipDesc(newNode.tip, true))
    currentNode['formDesc'].push(formatTitleDesc(newNode.label))
    // 控制换行
    currentNode.formDesc[0].break = true
  }
}

//获取业务单元编码
export const getCodeFromName = (orgList, orgName) => {
  let org = orgList.find(element => element.orgName === orgName)
  if (org) {
    //能找到，则是业务单元的
    return org.orgCode
  } else {
    //否则是集团总部
    org = orgList[0]?.children.find(element => element.orgName === orgName)
    if (org) {
      return org.orgCode
    }
  }
  return ''
}

export const getOrgFromCode = (orgList, orgCode) => {
  let org = orgList.find(element => element.orgCode === orgCode)
  if (org) {
    //能找到，则是业务单元的
    return org.orgName
  } else {
    //否则是集团总部
    org = orgList[0]?.children.find(element => element.orgCode === orgCode)
    if (org) {
      return org.orgName
    }
  }
  return ''
}
/**
 * 获取扁平化组织树
 * @param { } orgList
 * @returns
 */
export const getFlatOrg = orgList => {
  return JSON.parse(JSON.stringify(treeToFlat(orgList)))
}

export const treeToFlat = (tree, parentId = null) => {
  let flat = []
  for (let node of tree) {
    let copy = { ...node, parentId }
    flat.push(copy)
    if (node.children && node.children.length > 0) {
      flat = flat.concat(treeToFlat(node.children, node.id))
    }
  }
  return flat
}
